<template>
    <div class="order-apply-invoice">
      <div ref="chartContainer" id="barLine1Main" style="width: 100%; height: 400px;"></div>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, watch, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
const emits = defineEmits(['barClick']) // 定义点击事件
const props = defineProps({
  config: {
    type: Object,
    default: () =>({
      xAxisData: [],
      yAxisDataBar: [],
      yAxisDataLine: []
    })
  }
})

const chartContainer = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null
const initChart = ()=> {
  if (!chartContainer.value) return
  
  // 销毁旧实例
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  // 创建新实例
  chartInstance = echarts.init(chartContainer.value)

   // 添加点击事件监听
   chartInstance.on('click', 'series.bar', (params) => {
    // params 包含点击的柱状图数据信息
    emits('barClick', params )
  })
  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || !props.config) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: { color: '#999' }
      }
    },
    legend: {
      right: '100px',
      top: '0',
      data: ['已提回调箱量（个）', '已提回调箱量占比（%）']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Array.from(props.config.xAxisData),
      axisPointer: {
        type: 'shadow'
      },
      // axisLabel: {
      //   rotate: 30, // 标签旋转防止重叠
      //   interval: 0 // 强制显示所有标签
      // }
    },
    yAxis: [
      {
        type: 'value',
        name: '箱量',
        min: 0,
        axisLabel: {
          formatter: '{value}个'
        },
        axisLine: {
          show: true
        }
      },
      {
        type: 'value',
        name: '占比',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        },
        axisLine: {
          show: true
        },
        splitLine: {
          show: false // 避免与左侧y轴网格线重叠
        }
      }
    ],
    series: [
      {
        name: '已提回调箱量（个）',
        type: 'bar',
        barWidth: '40%', // 控制柱状图宽度
        tooltip: {
          valueFormatter: (value: number) => `${value}个`
        },
        data: Array.from(props.config.yAxisDataBar),
        label: {
          show: true,
          position: 'top',
          formatter: '{c}个'
        }
      },
      {
        name: '已提回调箱量占比（%）',
        type: 'line',
        yAxisIndex: 1, // 使用右侧y轴
        smooth: true, // 平滑曲线
        tooltip: {
          valueFormatter: (value: number) => `${value}%`
        },
        data: props.config.yAxisDataLine,
        label: {
          show: true,
          formatter: '{c}%'
        },
        symbol: 'circle', // 数据点形状
        symbolSize: 8, // 数据点大小
        lineStyle: {
          width: 3,
          color: '#ff7f0e'
        },
        itemStyle: {
          color: '#ff7f0e'
        }
      }
    ],
    // dataZoom: [ // 添加数据区域缩放
    //   {
    //     type: 'slider',
    //     show: true,
    //     xAxisIndex: [0],
    //     start: 0,
    //     end: 100
    //   }
    // ]
  }
  
  chartInstance.setOption(option)
  chartInstance.resize() // 确保图表正确渲染
}



// 监听配置变化
watch(() => props.config, () => {
  if (props.config.xAxisData?.length > 0) {
    if (!chartInstance) {
      initChart()
    } else {
      updateChart()
    }
  }
}, { deep: true })

// 组件挂载时初始化
onMounted(() => {
  nextTick(() => {
    if (props.config.xAxisData?.length > 0) {
      initChart()
    }
  })
})

// 组件卸载时清理
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>
<style lang="scss" scoped></style>